const mongoose = require('mongoose')
const Schema = mongoose.Schema
let ObjectId = Schema.Types.ObjectId
const bcrypt = require('bcrypt')

const SALT_WORK_FACTOR = 10

// 创建UserSchema
const userSchema = new Schema({
  UserId: {type: ObjectId},
  username: {unique: true, type: String},
  password: String,
  createAt: {type: Date, default: Date.now()},
  lastLoginAt: {type: Date, default: Date.now()}
}, {
  collection: 'user'
})

// 类似预处理，加盐并用hash加密
userSchema.pre('save', function (next) { // 注意，这里不能使用箭头函数，原因不详
  bcrypt.genSalt(SALT_WORK_FACTOR, (err, salt) => {
    if (err) return next(err)
    bcrypt.hash(this.password, salt, (err, hash) => {
      if (err) return next(err)
      this.password = hash
      next()
    })
  })
})

// 给userSchema创建一个方法，用于加盐加密对比加密前端传过来的密码
userSchema.methods = {
  // _password客户端，password数据库
  comparePassword: (_password, password) => {
    return new Promise((resolve, reject) => {
      bcrypt.compare(_password, password, (err, isMatch) => {
        if (!err) resolve(isMatch)
        else reject(err)
      })
    })
  }
}

// 发布模型
mongoose.model('User', userSchema)
